package tencent_practice;

import structure.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 判断一个链表中是否存在环
 */
public class Tencent_141_hasCycle {
    /**
     * 使用额外内存
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

    /**
     * 不使用额外空间
     * @param head
     * @param noUse
     * @return
     */
    public boolean hasCycle(ListNode head, boolean noUse) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode low = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            low = low.next;
            if (fast == low) {
                return true;
            }
        }
        return false;
    }
}
